package com.endurance.controller;

import com.endurance.vo.QueryVO;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;

@Controller
@RequestMapping("/param")
public class Test02ParameterBindingController {


    /**
     * 1.默认参数类型的绑定
     */
    @RequestMapping("list.do")
    public String list(HttpServletRequest request,
                       HttpServletResponse response,
                       HttpSession session,
                       Model model,
                       ModelMap modelMap) {
        // 把值存放到request域中
        request.setAttribute("name", "xiaolin");
        // 把值存放在Model中
        model.addAttribute("age", 18);
        // 把值存放在Session中
        session.setAttribute("sex", "男");

        HashMap<String, String> hashMap = new HashMap<String, String>();
        hashMap.put("hobby", "java");
        hashMap.put("address", "山东省");
        // 把值存放在ModelMap中
        modelMap.addAttribute("hashMap", hashMap);
        return "user";
    }


    /**
     * 2.简单类型绑定： int、Integer、String、boolean
     */
    @RequestMapping(value = "list2.do", method = RequestMethod.POST)
    public String list2(Model model, @RequestParam("name") String name, String age) {
        model.addAttribute("name", name);
        model.addAttribute("age", age);
        return "user";
    }

    /**
     * 3.VO类型的参数绑定
     * 前端提交的参数名需要和属性名一一对应
     */
    @RequestMapping(value = "list3.do", method = RequestMethod.POST)
    public String list3(Model model, QueryVO queryVO) {
        model.addAttribute("name", queryVO.getName());
        model.addAttribute("age", queryVO.getAge());
        model.addAttribute("username", queryVO.getUser().getUsername());
        return "user";
    }

    /**
     * 4. 数组类型
     * 前端提交多个相同的参数名会绑定到一个数组中
     */
    @RequestMapping(value = "list4.do", method = RequestMethod.POST)
    public void list4(String[] hobby) {
        for (int i = 0; i < hobby.length; i++) {
            System.out.println(hobby[i]);
        }
    }


    @RequestMapping(value = "list5.do", method = RequestMethod.POST)
    public String list5(Model model, @RequestBody QueryVO queryVO) {
        model.addAttribute("name", queryVO.getName());
        model.addAttribute("age", queryVO.getAge());
         return "user";
    }

}
